import { Worker as JestWorker } from "jest-worker";
import styletexttocssrulesstrings from "../src/styletexttocssrulesstrings.cjs";
// import { Deduplication } from "../src/Deduplication";

let mathworker: undefined | JestWorker;
export const defaultopts = {
    em: 16,
    ex: 8.633333333333333,
    containerWidth: 1261.3333740234375,
    lineWidth: 1000000,
    scale: 1.2207767722473604,
    family: "",
};
export async function terminateworker() {
    let lastworker = mathworker;
    mathworker = void 0;
    await lastworker?.end();
}
async function createworker() {
    const path = await import("path");
    const { fileURLToPath } = await import("url");
    var __dirname = path.resolve(path.dirname(fileURLToPath(import.meta.url)));
    return new JestWorker(path.resolve(__dirname, "./mathjax-worker.cjs"));
}
/**
 *
 * @param code 数学代码
 * @param language 数学语言
 * @param container 元素容器
 * @param stylecssrules 样式规则
 */
export default async function rendermathjax(
    code: string,
    language: "latex" | "mathml" | "asciimath",
    container: HTMLElement,
    stylecssrules: Set<string>
) {
    mathworker = mathworker || (await createworker());

    // console.log(mathworker);
    const rendermath: (
        code: string,
        language: string,
        opts?: object
    ) => Promise<{
        html: string;
        css: string;
    }> = Reflect.get(mathworker, "rendermath").bind(mathworker);

    const { html, css } = await rendermath(code, language, defaultopts);

    container.insertAdjacentHTML("beforeend", html);
    const rawstyletext = css;
    const stylesheetset = stylecssrules;
    styletexttocssrulesstrings(rawstyletext).forEach((s) => {
        stylesheetset.add(s);
    });
}
